package com.hu.system.service.impl;

import com.hu.common.utils.SecurityUtils;
import com.hu.common.utils.StringUtils;
import com.hu.system.domain.ShopInfo;
import com.hu.system.mapper.ShopInfoMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.service.IShopInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺信息Service业务层处理
 *
 * @author hu
 * @date 2025-01-21
 */
@Service
public class ShopInfoServiceImpl implements IShopInfoService {

    @Autowired
    private ShopInfoMapper shopInfoMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    /**
     * 查询店铺信息列表
     *
     * @param shopInfo 店铺信息
     * @return 店铺信息
     */
    @Override
    public List<ShopInfo> selectShopInfoList(ShopInfo shopInfo) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 管理员（userId为1）可以查看所有店铺
        if (userId != null && userId == 1L) {
            return shopInfoMapper.selectShopInfoList(shopInfo);
        }

        // 普通用户只能查看自己绑定的店铺
        List<Long> userShopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (userShopIds == null || userShopIds.isEmpty()) {
            // 用户没有绑定任何店铺，返回空列表
            return new ArrayList<>();
        }

        // 查询所有店铺，然后过滤出用户绑定的店铺
        List<ShopInfo> allShops = shopInfoMapper.selectShopInfoList(shopInfo);
        return allShops.stream()
                .filter(shop -> userShopIds.contains(shop.getShopId()))
                .collect(Collectors.toList());
    }

    /**
     * 根据店铺ID查询店铺信息
     *
     * @param shopId 店铺ID
     * @return 店铺信息
     */
    @Override
    public ShopInfo selectShopInfoByShopId(Long shopId) {
        ShopInfo shopInfo = shopInfoMapper.selectShopInfoByShopId(shopId);

        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 管理员可以查看所有店铺
        if (userId != null && userId == 1L) {
            return shopInfo;
        }

        // 普通用户只能查看自己绑定的店铺
        List<Long> userShopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (userShopIds != null && userShopIds.contains(shopId)) {
            return shopInfo;
        }

        // 没有权限查看该店铺
        return null;
    }

    /**
     * 新增店铺信息
     *
     * @param shopInfo 店铺信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertShopInfo(ShopInfo shopInfo) {
        return shopInfoMapper.insertShopInfo(shopInfo);
    }

    /**
     * 修改店铺信息
     *
     * @param shopInfo 店铺信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateShopInfo(ShopInfo shopInfo) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 管理员可以修改所有店铺
        if (userId != null && userId == 1L) {
            return shopInfoMapper.updateShopInfo(shopInfo);
        }

        // 普通用户只能修改自己绑定的店铺
        List<Long> userShopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (userShopIds == null || !userShopIds.contains(shopInfo.getShopId())) {
            throw new com.hu.common.exception.ServiceException("无权修改该店铺信息");
        }

        return shopInfoMapper.updateShopInfo(shopInfo);
    }

    /**
     * 批量删除店铺信息
     *
     * @param shopIds 需要删除的店铺ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteShopInfoByShopIds(Long[] shopIds) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 管理员可以删除所有店铺
        if (userId == null || userId != 1L) {
            // 普通用户只能删除自己绑定的店铺
            List<Long> userShopIds = userShopMapper.selectShopIdsByUserId(userId);
            for (Long shopId : shopIds) {
                if (userShopIds == null || !userShopIds.contains(shopId)) {
                    throw new com.hu.common.exception.ServiceException("无权删除店铺ID为" + shopId + "的店铺");
                }
            }
        }

        // 删除店铺时，同时删除用户店铺关联关系
        for (Long shopId : shopIds) {
            userShopMapper.deleteUserShopByShopId(shopId);
        }
        return shopInfoMapper.deleteShopInfoByShopIds(shopIds);
    }

    /**
     * 校验店铺编码是否唯一
     *
     * @param shopInfo 店铺信息
     * @return 结果
     */
    @Override
    public boolean checkShopCodeUnique(ShopInfo shopInfo) {
        Long shopId = StringUtils.isNull(shopInfo.getShopId()) ? -1L : shopInfo.getShopId();
        ShopInfo info = shopInfoMapper.checkShopCodeUnique(shopInfo.getShopCode());
        if (StringUtils.isNotNull(info) && info.getShopId().longValue() != shopId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 根据店铺名称查询店铺信息
     * 
     * @param shopName 店铺名称
     * @return 店铺信息
     */
    @Override
    public ShopInfo selectShopInfoByShopName(String shopName) {
        return shopInfoMapper.selectShopInfoByShopName(shopName);
    }

    /**
     * 根据店铺名称获取或创建店铺（防重复创建）
     * 导入时使用，如果店铺不存在则自动创建
     * 
     * @param shopName 店铺名称
     * @param createBy 创建人
     * @return 店铺信息
     */
    @Override
    @Transactional
    public ShopInfo getOrCreateShopByName(String shopName, String createBy) {
        if (StringUtils.isEmpty(shopName)) {
            throw new com.hu.common.exception.ServiceException("店铺名称不能为空");
        }

        // 先查询是否存在（包括已删除的）
        ShopInfo shop = shopInfoMapper.selectShopInfoByShopNameIncludeDeleted(shopName);

        if (shop != null) {
            // 店铺已存在，直接返回
            return shop;
        }

        // 店铺不存在，创建新店铺
        shop = new ShopInfo();
        shop.setShopName(shopName);
        // 自动生成店铺编码：使用店铺名称拼音或时间戳
        shop.setShopCode("SHOP_" + System.currentTimeMillis());
        shop.setStatus("0");  // 0=正常
        shop.setCreateBy(createBy);

        try {
            shopInfoMapper.insertShopInfo(shop);
            return shop;
        } catch (Exception e) {
            // 捕获唯一索引冲突异常（并发创建时）
            if (e.getMessage() != null && (e.getMessage().contains("Duplicate") || e.getMessage().contains("duplicate"))) {
                // 重新查询并返回
                shop = shopInfoMapper.selectShopInfoByShopNameIncludeDeleted(shopName);
                if (shop != null) {
                    return shop;
                }
            }
            // 其他异常抛出
            throw new com.hu.common.exception.ServiceException("创建店铺失败：" + e.getMessage());
        }
    }
}

